package com.example.onlinetaxi.ui.activity.Driver.MainPage.OrderFragments;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.onlinetaxi.LocalStroage.LocalStorage;
import com.example.onlinetaxi.R;
import com.example.onlinetaxi.Thread.DriverGetCancelThread;
import com.example.onlinetaxi.callback.DriverCallBack.ICancelDrive;
import com.example.onlinetaxi.callback.OrderCallBack.GetOrderCallBack;
import com.example.onlinetaxi.callback.OrderCallBack.OrderCallBack;
import com.example.onlinetaxi.callback.OrderCallBack.ReceivedOrderCallBack;
import com.example.onlinetaxi.dto.DataResponse;
import com.example.onlinetaxi.dto.OrderDto.ReceivedOrderDto;
import com.example.onlinetaxi.ui.activity.DriverToStartPage.DriverToStartActivity;
import com.example.onlinetaxi.ui.activity.StartToEndPage.StartToEndActivity;
import com.example.onlinetaxi.util.OKHttpUtil.GetDataResponse;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;
import com.example.onlinetaxi.view.Adapter.DriverDoing1OrderAdapter;
import com.example.onlinetaxi.view.Adapter.WaitingOrderAdapter;
import com.example.onlinetaxi.view.Dialog.MyDialog;
import com.example.onlinetaxi.view.Dialog.PhoneDialog;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DriverDoing1OrderFragment extends Fragment {
    private View rootView;
    // 无订单提醒
    private TextView empty;
    // 订单列表
    private List<ReceivedOrderDto> orderList = new ArrayList<>();
    // 重新获取订单
    private GetOrderCallBack getOrderCallBack;
    // 请求参数列表
    private Map<String, String> map = new HashMap<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_driver_doing1_order, container, false);

        initView();

        initEvent();

        return rootView;
    }

    private void initEvent() {
        // 初始化订单列表控件
        initRecyclerView();

        // 初始化线程，启动接收用户是否取消接单的线程(至少有订单才会初始化)
        if (orderList.size() == 1 && DriverGetCancelThread.thread == null) {
            // 司机启动线程，监视订单状态，以防乘客取消
            DriverGetCancelThread.iCancelDrive = new ICancelDrive() {
                @Override
                public void cancelDrive(String cancelReason) {
                    // 弹出确认对话框
                    showCancelDialog(cancelReason);
                }
            };
            DriverGetCancelThread.finished = false;
            DriverGetCancelThread.thread = new Thread(new DriverGetCancelThread.GetOrderState());
            DriverGetCancelThread.thread.start();
        }

        if (orderList.size() != 0) {
            empty.setVisibility(View.INVISIBLE);
        } else {
            empty.setVisibility(View.VISIBLE);
        }
    }

    private void initRecyclerView() {
        // 找到布局文件中的recyclerView
        RecyclerView recyclerView = rootView.findViewById(R.id.driver_doing_1_order_list);
        /*指定RecyclerView布局方式*/
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        /*指定为LinearLayout布局*/
        recyclerView.setLayoutManager(layoutManager);
        /*适配去管理滑动显示*/
        DriverDoing1OrderAdapter adapter = new DriverDoing1OrderAdapter(orderList);

        // 设置点击事件
        adapter.setReceivedOrderCallBack(new ReceivedOrderCallBack() {
            @Override
            public void jump(ReceivedOrderDto order) {
                // 点击订单页面跳转
                // 跳转到等待接车
                startActivity(new Intent(getActivity(), DriverToStartActivity.class));
            }

            @Override
            public void clickButton(ReceivedOrderDto order) {
                // 显示输入手机号功能
                showDialog(order);
            }
        });

        // 设置适配器
        recyclerView.setAdapter(adapter);
    }

    // 我已接到乘客按钮
    private void showDialog(ReceivedOrderDto order) {
        View.OnClickListener onCancelClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 不进行操作
            }
        };

        View.OnClickListener onConfirmClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取司机输入
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(PhoneDialog.Builder.num_in1_et.getText());
                stringBuffer.append(PhoneDialog.Builder.num_in2_et.getText());
                stringBuffer.append(PhoneDialog.Builder.num_in3_et.getText());
                stringBuffer.append(PhoneDialog.Builder.num_in4_et.getText());

                // 验证司机输入是否正确
                if (verifyPhone_4(stringBuffer.toString())) {
                    // 销毁司机启动线程
                    DriverGetCancelThread.finished = true;
                    DriverGetCancelThread.thread = null;
                    DriverGetCancelThread.iCancelDrive = null;

                    // 发送前往目的地信息
                    goingToDestination();
                    // 跳转到司机前往界面
                    startActivity(new Intent(getActivity(), StartToEndActivity.class));
                    // 刷新当前界面
                    refresh();
                }
            }
        };

        // 显示提示框
        PhoneDialog.showInfoDialog(getActivity(), onCancelClickListener, onConfirmClickListener);
    }

    private void goingToDestination() {
        map.clear();

        // 传入订单编号
        map.put("orderId", LocalStorage.currentOrder.getReceivedOrderId().toString());

        // 发起前往终点请求，改变订单状态
        OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "receivedOrder", "goingToDestination");

        // 修改当前订单状态
        LocalStorage.currentOrder.setState("4");
    }

    private boolean verifyPhone_4(String phone_4) {
        // 将后四位手机号发送到后台，验证手机号
        map.clear();
        map.put("phone_4", phone_4);
        map.put("orderId", LocalStorage.currentOrderId);

        String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "receivedOrder", "verifyPhone_4");
        // 获取响应体
        DataResponse dataResponse = GetDataResponse.getDataResponse(response);

        if (dataResponse.getCode().equals("200")) {
            return true;
        } else {
            Toast.makeText(getActivity(), dataResponse.getData().get("error").toString(), Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    private void showCancelDialog(String cancelReason) {
        View.OnClickListener onCancelClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 拒绝用户的请求
                disagree();

                // 重新启动线程
                DriverGetCancelThread.thread = new Thread(new DriverGetCancelThread.GetOrderState());
                DriverGetCancelThread.thread.start();
            }
        };

        View.OnClickListener onConfirmClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 同意用户的请求
                agree();

                // 刷新界面
                refresh();
            }
        };

        if (cancelReason.equals("")) {
            cancelReason = "无";
        }

        // 显示提示框
        Looper.prepare();
        MyDialog.drawable = getContext().getDrawable(R.drawable.dialog_confirm_driver);
        MyDialog.showInfoDialog(getActivity(), "用户申请取消订单，理由:" + cancelReason, "拒绝", onCancelClickListener, "同意", onConfirmClickListener);
        Looper.loop();
    }

    private void agree() {
        map.clear();
        map.put("orderId", LocalStorage.currentOrder.getReceivedOrderId().toString());
        map.put("cancelState", "2");

        OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "receivedOrder", "setDriverCancel");

        // 关闭线程
        DriverGetCancelThread.finished = false;
        DriverGetCancelThread.thread = null;

        // 删除保存本地的订单数据
        LocalStorage.chosenOrder = null;
        LocalStorage.currentOrderId = null;
        LocalStorage.currentOrder = null;
    }

    private void disagree() {
        map.clear();
        map.put("orderId", LocalStorage.currentOrder.getReceivedOrderId().toString());
        map.put("cancelState", "3");

        OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "receivedOrder", "setDriverCancel");

        // 关闭线程
        DriverGetCancelThread.finished = false;
        DriverGetCancelThread.thread = null;

    }

    private void refresh() {
        // 重新获取order列表
        getOrderCallBack.refreshOrder();

        // 刷新当前页面
        initEvent();
    }

    private void initView() {
        empty = rootView.findViewById(R.id.driver_doing_1_order_empty);

        if (orderList.size() != 0) {
            empty.setVisibility(View.INVISIBLE);
        }
    }

    public void setOrderList(List<ReceivedOrderDto> orderList) {
        this.orderList = orderList;
    }

    public void setGetOrderCallBack(GetOrderCallBack getOrderCallBack) {
        this.getOrderCallBack = getOrderCallBack;
    }
}